package com.ruoyi.framework.web.service

import com.ruoyi.common.core.domain.entity.SysRole
import com.ruoyi.common.core.domain.entity.SysUser
import com.ruoyi.system.service.ISysMenuService
import com.ruoyi.system.service.ISysRoleService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import org.springframework.util.CollectionUtils

/**
 * 用户权限处理
 *
 * @author ruoyi
 */
@Component
class SysPermissionService {
    @Autowired
    private lateinit var roleService: ISysRoleService

    @Autowired
    private lateinit var menuService: ISysMenuService

    /**
     * 获取角色数据权限
     *
     * @param user 用户信息
     * @return 角色权限信息
     */
    fun getRolePermission(user: SysUser): Set<String> {
        val roles: MutableSet<String> = mutableSetOf()
        // 管理员拥有所有权限
        if (user.isAdmin) {
            roles.add("admin")
        } else {
            roles.addAll(roleService.selectRolePermissionByUserId(user.userId))
        }
        return roles
    }

    /**
     * 获取菜单数据权限
     *
     * @param user 用户信息
     * @return 菜单权限信息
     */
    fun getMenuPermission(user: SysUser?): Set<String> {
        val perms: MutableSet<String> = mutableSetOf()
        // 管理员拥有所有权限
        if (user!!.isAdmin) {
            perms.add("*:*:*")
        } else {
            val roles: List<SysRole?>? = user.roles
            if (!CollectionUtils.isEmpty(roles)) {
                // 多角色设置permissions属性，以便数据权限匹配权限
                for (role in roles!!) {
                    val rolePerms = menuService.selectMenuPermsByRoleId(role!!.roleId)
                    role.permissions = rolePerms
                    perms.addAll(rolePerms)
                }
            } else {
                perms.addAll(menuService.selectMenuPermsByUserId(user.userId))
            }
        }
        return perms
    }
}
